package org.example;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Collections;
// import com.sun.deploy.util.StringUtils;
// import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.lang.StringUtils;

public class Tianzhenlan {
    public static String generateSign(Map<String, String> params, String appSecret, String signMethod) {
        // 第一步：参数排序
        List<String> keys = new ArrayList<String>(params.keySet());;
        Collections.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotEmpty(appSecret)) {
            sb.append(appSecret);
        }

        int index = 0;
        for (String key : keys) {
            String value = params.get(key).trim();
            if ("sign".equals(key) || StringUtils.isEmpty(value)) {
                continue;
            }
            sb.append(index == 0 ? "" : "&").append(key).append("=").append(value);
            index++;
        }

        if (StringUtils.isNotEmpty(appSecret)) {
            sb.append(appSecret);
        }
        String encryptionKey = sb.toString().trim();

        // 第三步：加签
        if ("MD5".equals(signMethod)) {
            try {
                return genMd5(encryptionKey);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        } else {
            // 暂不需支持，支持MD5即可
            return "";
        }
    }

    public static String genMd5(String info) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] infoBytes = info.getBytes();
        md5.update(infoBytes);
        byte[] sign = md5.digest();
        return byteArrayToHex(sign);
    }

    public static String byteArrayToHex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(aByte & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }
}
